package com.nf.health.app.datamain.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.customview.MenuPopupWindow;
import com.nf.health.app.models.BluetoothDeviceAttr;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bluetools.ProtocolParser;

/**
 * Created by hepan on 2016/3/21.
 * The only genius that is worth anything is the genius for hard work
 * <p/>
 * 尿检
 */
public class UrineTestActivity extends BaseActivity implements View.OnTouchListener {

    private static final long INTERVAL_TIME = 5 * 1000;
    private static final String FLAG_ADD_URINE = "flag_add_urine";

    @Bind(R.id.tv_history_data)
    TextView tvHistoryData;
    @Bind(R.id.btn_measure)
    Button btnMeasure;
    @Bind(R.id.titlebar_title_tv)
    TextView titlebarTitleTv;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.tv_putaotang_value)
    TextView tvPutaotangValue;
    @Bind(R.id.tv_danhongsu_value)
    TextView tvDanhongsuValue;
    @Bind(R.id.tv_dongti_value)
    TextView tvDongtiValue;
    @Bind(R.id.tv_bizhong_value)
    TextView tvBizhongValue;
    @Bind(R.id.tv_hongxibao_value)
    TextView tvHongxibaoValue;
    @Bind(R.id.tv_ph_value)
    TextView tvPhValue;
    @Bind(R.id.tv_niaodanbai_value)
    TextView tvNiaodanbaiValue;
    @Bind(R.id.tv_niaodanyuan_value)
    TextView tvNiaodanyuanValue;
    @Bind(R.id.tv_yaxiaosuanyan_value)
    TextView tvYaxiaosuanyanValue;
    @Bind(R.id.tv_baixibao_value)
    TextView tvBaixibaoValue;
    @Bind(R.id.et_alert)
    TextView etAlert;


    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothAdapter mBluetoothAdapter;
    // 蓝牙服务类
    private BluetoothLeService mBluetoothLeService;
    private List<BluetoothDevice> devices = new ArrayList<>();

    private Handler mHandler = new Handler();
    private ServiceConnection mServiceConnection;

    private StringBuilder sb = new StringBuilder();

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        public static final String TAG = "mGattUpdateReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                showToast("蓝牙连接断开,请重试");
                hideLoading();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {

            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (data == null) {
                    return;
                }
                LogUtil.e(TAG, ProtocolParser.binaryToHexString(data) + ">>>>" + data.length);
                try {
                    handleUrineData(data);
                } catch (Exception e) {
                    LogUtil.exception(e);
                }
            }
        }
    };

    private void handleUrineData(byte[] data) {
        String str = Util.toStringHex(ProtocolParser.bytes2HexString(data));
        if (!TextUtils.isEmpty(str)) {
            sb.append(str);
        }
        if (sb.toString().length() == 35 && sb.toString().contains(" ")) {
            hideLoading();
            String result = sb.toString().replace(" ", "");
            int index = 5;
            int putaotangIndex = Integer.parseInt(result.substring(index, ++index));
            int danhongsuIndex = Integer.parseInt(result.substring(++index, ++index));
            int dongtiIndex = Integer.parseInt(result.substring(++index, ++index));
            int bizhongIndex = Integer.parseInt(result.substring(++index, ++index));
            int hongxibaoIndex = Integer.parseInt(result.substring(++index, ++index));
            int phIndex = Integer.parseInt(result.substring(++index, ++index));
            int niaodanbaiIndex = Integer.parseInt(result.substring(++index, ++index));
            int niaodanyuanIndex = Integer.parseInt(result.substring(++index, ++index));
            int yaxiaosuanyanIndex = Integer.parseInt(result.substring(++index, ++index));
            int baixibaoIndex = Integer.parseInt(result.substring(++index, ++index));

            sb.delete(0, sb.toString().length());

            String putaotangValue = BluetoothDeviceAttr.valueArray[putaotangIndex];
            String danhongsuVlaue = BluetoothDeviceAttr.valueArray[danhongsuIndex];
            String dongtiValue = BluetoothDeviceAttr.valueArray[dongtiIndex];
            String bizhongValue = BluetoothDeviceAttr.scaleArray[bizhongIndex];
            String hongxibaoValue = BluetoothDeviceAttr.valueArray[hongxibaoIndex];
            String phValue = BluetoothDeviceAttr.phArray[phIndex];
            String niaodanbaiValue = BluetoothDeviceAttr.valueArray[niaodanbaiIndex];
            String niaodanyuanValue = BluetoothDeviceAttr.niaoDanYuanArray[niaodanyuanIndex];
            String yaxiaosuanyanValue = BluetoothDeviceAttr.valueArray[yaxiaosuanyanIndex];
            String baixibaoValue = BluetoothDeviceAttr.valueArray[baixibaoIndex];

            //TODO 显示到ListView中
            tvPutaotangValue.setText(putaotangValue);
            tvDanhongsuValue.setText(danhongsuVlaue);
            tvDongtiValue.setText(dongtiValue);
            tvBizhongValue.setText(bizhongValue);
            tvHongxibaoValue.setText(hongxibaoValue);
            tvPhValue.setText(phValue);
            tvNiaodanbaiValue.setText(niaodanbaiValue);
            tvNiaodanyuanValue.setText(niaodanyuanValue);
            tvYaxiaosuanyanValue.setText(yaxiaosuanyanValue);
            tvBaixibaoValue.setText(baixibaoValue);

            /**
             * 把数据组合成字符串存储到sp
             */
            String uniteResult = putaotangValue + ","
                    + danhongsuVlaue + ","
                    + dongtiValue + ","
                    + bizhongValue + ","
                    + hongxibaoValue + ","
                    + phValue + ","
                    + niaodanbaiValue + ","
                    + niaodanyuanValue + ","
                    + yaxiaosuanyanValue + ","
                    + baixibaoValue;
            PreferenceHelper.putString(PreferenceHelper.URINE_TEST_MEASURED_INFO, uniteResult);

            provider.requestAddDeviceUrine(putaotangValue, danhongsuVlaue, dongtiValue, bizhongValue, hongxibaoValue, phValue, niaodanbaiValue, niaodanyuanValue, yaxiaosuanyanValue, baixibaoValue, "2", FLAG_ADD_URINE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContent(R.layout.activity_urine_test_data);
        setTitleBar(R.layout.layout_common_header);
        ButterKnife.bind(this);

        initView();
        initListener();

        initBluetooth();
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if (FLAG_ADD_URINE.equals(actionName)){
            hideLoading();
            showToast("数据上传成功");
            /**
             * 数据上传成功 跳转到展示结果类
             */
            ActivityUtils.showActivity(this, UrineTestMeasuredResultActivity.class);
            provider.requestAddScore("13", "");//添加积分
        }

    }

    private void initBluetooth() {

        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持蓝牙4.0通讯");
            finish();
            return;
        }

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            showToast("没有发现蓝牙模块");
            finish();
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //过滤出血糖仪
                            if(device != null){
                                if(!TextUtils.isEmpty(device.getName())){
                                    if(device.getName().contains(BluetoothDeviceAttr.URINE_DEVICE_NAME)){
                                        if (!devices.contains(device)) {
                                            devices.add(device);
                                        }
                                    }
                                }
                            }
                            /*if (device != null && device.getName().contains(BluetoothDeviceAttr.URINE_DEVICE_NAME)) {
                                if (!devices.contains(device)) {
                                    devices.add(device);
                                }
                            }*/
                        }
                    });
                }
            };
        } else {
            showToast("设备蓝牙版本过低");
            finish();
            return;
        }
        bindLeService();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                if (!mBluetoothLeService.initialize()) {
                    new MaterialDialog.Builder(UrineTestActivity.this)
                            .title("提示")
                            .content("蓝牙初始化服务失败了~")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(MaterialDialog dialog, DialogAction which) {
                                    finish();
                                }
                            })
                            .show();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bleService.putExtra("type", DeviceData.Type.URINE);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        tvHistoryData.setOnClickListener(this);
        btnMeasure.setOnClickListener(this);
        etAlert.setOnTouchListener(this);

    }

    /**
     * 初始化view
     */
    private void initView() {
        //设置标题栏
        titlebarTitleTv.setText("尿检仪数据");
        titlebarRightView.setVisibility(View.VISIBLE);
        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.ic_title_setting);

        //回显最近测量的数据
        showlatestMeasuredData();
    }

    private void showlatestMeasuredData() {
        String result = PreferenceHelper.getString(PreferenceHelper.URINE_TEST_MEASURED_INFO, "");
        String[] detailResult = result.split(",");
        if (detailResult.length == 10) {
            tvPutaotangValue.setText(detailResult[0]);        //葡萄糖
            tvDanhongsuValue.setText(detailResult[1]);        //胆红素
            tvDongtiValue.setText(detailResult[2]);           //酮体
            tvBizhongValue.setText(detailResult[3]);          //比重
            tvHongxibaoValue.setText(detailResult[4]);        //红细胞
            tvPhValue.setText(detailResult[5]);               //PH
            tvNiaodanbaiValue.setText(detailResult[6]);       //尿蛋白
            tvNiaodanyuanValue.setText(detailResult[7]);      //尿胆原
            tvYaxiaosuanyanValue.setText(detailResult[8]);    //亚硝酸盐
            tvBaixibaoValue.setText(detailResult[9]);         //白细胞

            etAlert.setText(getAlertString(detailResult));
        } else {
            tvPutaotangValue.setText("无数据");        //葡萄糖
            tvDanhongsuValue.setText("无数据");        //胆红素
            tvDongtiValue.setText("无数据");           //酮体
            tvBizhongValue.setText("无数据");          //比重
            tvHongxibaoValue.setText("无数据");        //红细胞
            tvPhValue.setText("无数据");               //PH
            tvNiaodanbaiValue.setText("无数据");       //尿蛋白
            tvNiaodanyuanValue.setText("无数据");      //尿胆原
            tvYaxiaosuanyanValue.setText("无数据");    //亚硝酸盐
            tvBaixibaoValue.setText("无数据");         //白细胞
            etAlert.setText("还没有测量数据,不能给出健康提示");
        }
    }

    /**
     * 根据测量数据获得健康提示
     * @param detailResult 十种数据的集合
     * @return
     */
    private String getAlertString(String[] detailResult) {
        String result = "";
        if (detailResult[0].contains("+")){//葡萄糖
            result += getResources().getString(R.string.putaotang);
            result += "\r\n";
        }

        if (detailResult[1].contains("+")){//胆红素
            result += getResources().getString(R.string.danhongsu);
            result += "\r\n";
        }

        if (detailResult[2].contains("+")){//酮体
            result += getResources().getString(R.string.tongti);
            result += "\r\n";
        }

        if (detailResult[4].contains("+")){//红细胞
            result += getResources().getString(R.string.hongxibao);
            result += "\r\n";
        }

        if (detailResult[6].contains("+")){//尿蛋白
            result += getResources().getString(R.string.niaodanbai);
            result += "\r\n";
        }

        if (Float.valueOf(detailResult[7]) > 1.0f){//尿胆原
            result +=  getResources().getString(R.string.niaodanyuan);
            result += "\r\n";
        }

        if (!detailResult[8].equals("-")){//亚硝酸盐
            result += getResources().getString(R.string.yaxiaosuanyan);
            result += "\r\n";
        }

        if (detailResult[9].contains("+")){//白细胞
            result += getResources().getString(R.string.baixibao);
            result += "\r\n";
        }
        if (TextUtils.isEmpty(result)){
            return "指标正常,祝君健康";
        }
        return result;
    }

    /**
     * 初始化绑定设备弹窗
     */
    private void initPop() {
        MenuPopupWindow pop = new MenuPopupWindow(this, PreferenceHelper.getString(PreferenceHelper.URINE_NAME, ""), false);
        pop.showAsDropDown(titlebarRightView);
        pop.setOnMenuItemClickListener(new OnMyClickListener() {
            @Override
            public void onClick(int position, String flag) {
                if (R.id.ll_bind_device == position) {
                    if (PreferenceHelper.getBoolean(PreferenceHelper.URINE_IS_BING, false)) {
                        //TODO 解绑操作
                        PreferenceHelper.putBoolean(PreferenceHelper.URINE_IS_BING, false);
                        PreferenceHelper.putString(PreferenceHelper.URINE_ADDRESS, "");
                        PreferenceHelper.putString(PreferenceHelper.URINE_NAME, "");
                        showToast("解绑成功");
                        mBluetoothLeService.close();
                    } else {
                        scanLeDevice(true);
                    }
                } else if (R.id.tv_manual_input == position) {
                    showToast("AAC");
                }else if (R.id.tv_loadl_input == position) {
                   //Util.showNotHasFountDeviced(UrineTestActivity.this);
                    ActivityUtils.showActivity(UrineTestActivity.this,MyShopStoreActivity.class);
                }
            }
        });
    }

    private void scanLeDevice(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (enable) {
                showLoading("查找设备中..");
                devices.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                // Stops scanning after a pre-defined scan period.
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            hideLoading();
                            showBluetoothNames();
                        }
                    }


                }, INTERVAL_TIME);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                try {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } catch (Exception e) {
                }
            }
        }
    }

    private void showBluetoothNames() {
        if (devices.size() <= 0) {
           // new MaterialDialog.Builder(this).title("提示").content("没有发现尿检仪噢~").positiveText("确定").show();
            Util.showNotHasFountDeviced(UrineTestActivity.this);
            return;
        }
        String[] deviceNames = new String[devices.size()];
        for (int i = 0; i < devices.size(); i++) {
            String address = devices.get(i).getAddress();
            deviceNames[i] = "尿检仪-" + address.replace(":", "");
        }
        //mLeScanCallback 将搜索结果添加到集合中
        if(!isFinishing()) {
            new MaterialDialog.Builder(this)
                    .title("尿检仪")
                    .items(deviceNames)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//                        mBluetoothLeService.connect(devices.get(which).getAddress());
                            PreferenceHelper.putBoolean(PreferenceHelper.URINE_IS_BING, true);
                            PreferenceHelper.putString(PreferenceHelper.URINE_NAME, "尿检仪-" + devices.get(which).getAddress().replace(":", ""));
                            PreferenceHelper.putString(PreferenceHelper.URINE_ADDRESS, devices.get(which).getAddress());
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //右边按钮的点击事件
            case R.id.titlebar_right_view:
                initPop();
                break;
            //点击测量按钮
            case R.id.btn_measure:
                //如果没有绑定设备，则先进行搜索
                if (PreferenceHelper.getBoolean(PreferenceHelper.URINE_IS_BING, false)) {
                    showLoading("测量中");
                    mBluetoothLeService.connect(PreferenceHelper.getString(PreferenceHelper.URINE_ADDRESS, ""));
                } else {
                    initPop();
                }
                break;
            //点击历史记录按钮
            case R.id.tv_history_data:
                ActivityUtils.showActivity(this, UrineTestHistoryDataActivity.class);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, BluetoothLeService.makeGattUpdateIntentFilter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        mBluetoothLeService.close();
        mBluetoothLeService = null;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.et_alert:
                // 解决scrollView中嵌套EditText导致不能上下滑动的问题
                v.getParent().requestDisallowInterceptTouchEvent(true);
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_UP:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
        }
        return false;
    }
}
